package com.xiaojie.impl.message.impl;

import com.xiaojie.service.message.dto.AlarmMessageDto;
import com.xiaojie.service.message.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.List;

/**
 * @author xiaojie
 * @version 1.0
 * @description: TODO
 * @date 2022/4/29 17:31
 */
@Slf4j
@RestController
public class MessageServiceImpl implements MessageService {

    @Override
    public void send(String name) {
//        zipkin方式获取traceid
//        ServletRequestAttributes attributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = attributes.getRequest();
//        String traceId = request.getHeader("x-b3-traceid");
//        String spanId = request.getHeader("x-b3-spanid");
//        String parentSpanId = request.getHeader("x-b3-parentspanid");
//        log.info("message--------traceId:>>>>>>{},spanId>>>>>>{},parentSpanId>>>>>>{}",traceId,spanId,parentSpanId);
        // 获取request对象
        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes()).getRequest();
        getHeders(request);
        // 获取traceId skywalking方式
        String traceId = TraceContext.traceId();

        log.info("{}登录成功，发送通知,traceId>>>>>>>{}", name, traceId);
    }

    public static void getHeders(HttpServletRequest request) {
        //2.获得所有头的名称
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {//判断是否还有下一个元素
            String nextElement = headerNames.nextElement();//获取headerNames集合中的请求头
            String header2 = request.getHeader(nextElement);//通过请求头得到请求内容
        }
    }


    @Override
    public void send(List<AlarmMessageDto> alarmMessageList) {
        //实际生产中应当单独建立一个监控系统的服务，使用mq 发送短信，邮件或者微信公众号模板方式解决,此处只是演示
        for (AlarmMessageDto alarm : alarmMessageList) {
            log.info("报警信息为>>>>>>>>{}", alarm.getAlarmMessage());
        }
    }
}
